package com.wujie.springbootmongodb.service.impl;

import com.mongodb.client.result.UpdateResult;
import com.wujie.springbootmongodb.dao.StudentRepository;
import com.wujie.springbootmongodb.pojo.Student;
import com.wujie.springbootmongodb.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Student add(Student student) {
        Student student1 = studentRepository.save(student);
        return student1;
    }

    @Override
    public UpdateResult update(Student student) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        query.addCriteria(Criteria.where("_id").is(student.getId()));
        String collectionsName = "student";
        Update update = new Update();
        update.set("_id",student.getId());
        UpdateResult result = mongoTemplate.updateFirst(query, update, collectionsName);
        return result;
    }

    @Override
    public void delete(String id) {
        studentRepository.deleteById(id);
    }

    @Override
    public Student findByName(String name) {
       return studentRepository.findByName(name);
    }

    @Override
    public List<Student> findBySex(String sex) {
        return studentRepository.findBySex(sex);
    }
}
